package com.mehdiuz.backend.captcha.controller;

import com.mehdiuz.backend.captcha.entity.SliderCaptcha;
import com.mehdiuz.backend.captcha.service.CaptchaService;
import com.mehdiuz.backend.commons.utils.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/captcha")
public class CaptchaController {

    @Autowired
    private CaptchaService captchaService;

    @Autowired
    private JedisPool jedisPool;

    @GetMapping("pullCaptcha")
    public Result<SliderCaptcha> pullCaptcha(){
        SliderCaptcha captcha = captchaService.getCaptcha();
        return Result.ok(captcha);
    }

    @PostMapping("pushImage")
    public Result<Boolean> pushImage(@RequestBody List<SliderCaptcha> sliderCaptchas){
        return Result.ok(captchaService.putCaptcha(sliderCaptchas));
    }

    @PostMapping("checkCaptcha")
    public Result<Map<String,Object>> checkCaptcha(@RequestBody SliderCaptcha sliderCaptcha){
        Boolean b = captchaService.checkCaptcha(sliderCaptcha);
        if(b){
            Jedis jedis = jedisPool.getResource();
            Map<String,Object> map = new HashMap<>();
            try {
                String uuid = sliderCaptcha.getUuid();
                jedis.set(uuid,"true");
                jedis.expire(uuid,20);
                map.put("check",b);
                map.put("uuid",uuid);
            }catch (Exception e){
                e.printStackTrace();
            }finally {
                jedis.close();
            }
            return Result.ok(map);
        }else {
            return Result.fail();
        }
    }
}
